package com.example.demo.controller;

import com.example.demo.common.TokenCommon;
import com.example.demo.pojo.User;
import com.example.demo.service.RedisService;
import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;
import com.example.demo.util.MD5Util;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@RestController("login")
@RequestMapping("login")
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private RedisService redisService;

    @Resource
    private TokenService tokenService;

    private final TokenCommon tokenCommon = new TokenCommon();

    @PostMapping("password")
    public TokenCommon login(@RequestParam("email") String email,
                             @RequestParam("password") String password) {
        List<User> userList = this.userService.getUser(email);
        String md5 = MD5Util.md5(password);
        if (!userList.isEmpty()) {
            if (userList.get(0).getPassword().equals(md5)) {
                String token = this.tokenService.getToken(email, md5);
                return this.tokenCommon.tokenJSON(email, true, 200, token);
            }
            return this.tokenCommon.tokenJSON(email, false, 500, "密码错误！");
        }
        return this.tokenCommon.tokenJSON(email, false, 500, "账号不存在！");
    }

    @PostMapping("auth")
    public TokenCommon auth(@RequestParam("email") String email,
                            @RequestParam("auth") String auth) {
        List<User> userList = this.userService.getUser(email);
        String REDIS="AUTH1" + email;
        String s = this.redisService.get(REDIS);
        if (!userList.isEmpty()) {
            if (Objects.equals(auth, s)) {
                String token = this.tokenService.getToken(email, userList.get(0).getPassword());
                return this.tokenCommon.tokenJSON(email, true, 200, token);
            }

        } else {
            if (Objects.equals(auth, s)) {
                String hxPassword = this.userService.setUser(email);
                String Token = this.tokenService.getToken(email, hxPassword);
                this.redisService.delete(REDIS);
                return this.tokenCommon.tokenJSON(email, true, 200, Token);
            }
        }
        return this.tokenCommon.tokenJSON(email, false, 500, "验证码错误！");
    }
}
